﻿using UnityEngine;
using System.Collections;

public class ShayneMovementScript : MonoBehaviour 
{
	Vector2 playAreaLimits = new Vector3(10.0f,10.0f);
	LineRenderer myLine;
	Vector3 MoveToPos;
	
	public float rotateSpeed = 1.0f;
	public float StockMoveSpeed = 1.0f;
	public float currentMoveSpeed;
	public float jumpForce = 10.0f;
	
	
	// Use this for initialization
	void Start () 
	{
		myLine = GetComponent<LineRenderer> ();
		myLine.SetVertexCount(2);
		MoveToPos = transform.position + transform.forward;
		ResetSpeed ();
	}
	
	// Update is called once per frame
	void Update () 
	{
		MoveToLine ();
	}
	
	void MoveToLine()
	{
		Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		RaycastHit hitInfo;
		
		if(Physics.Raycast(ray, out hitInfo))
		{
			MoveToPos = new Vector3(hitInfo.point.x, transform.position.y, hitInfo.point.z);
			myLine.SetPosition (0, transform.position);
			myLine.SetPosition (1, MoveToPos);
		}
		else
		{
			myLine.SetPosition (0, transform.position);
			myLine.SetPosition (1, transform.position);
			MoveToPos = transform.position + transform.forward;
			KeepLineWithingLimits ();
		}


		
		Vector3 targetDir = MoveToPos - transform.position;
		Vector3 newDir = Vector3.RotateTowards (transform.forward, targetDir, rotateSpeed * Time.deltaTime, 0.0f);
		transform.LookAt (transform.position + newDir.normalized);
		
		transform.position += transform.forward * currentMoveSpeed * Time.deltaTime;
	}

	void KeepLineWithingLimits()
	{
		if(Mathf.Abs(MoveToPos.x) > playAreaLimits.x)
		{
			float offset = 0;
			if(MoveToPos.x > 0)
				offset = MoveToPos.x - playAreaLimits.x;
			else
				offset = MoveToPos.x + playAreaLimits.x;

			MoveToPos.x -= 2* offset;
		}

		if(Mathf.Abs(MoveToPos.z) > playAreaLimits.y)
		{
			float offset = 0;
			if(MoveToPos.z > 0)
				offset = MoveToPos.z - playAreaLimits.y;
			else
				offset = MoveToPos.z + playAreaLimits.y;
			
			MoveToPos.z -= 2* offset;
		}
	}
	
	void ResetSpeed()
	{
		currentMoveSpeed = StockMoveSpeed;
	}
	
	public void SetSpeed(float thrustSpeed, float Thrusttime)
	{
		currentMoveSpeed = thrustSpeed;
		Invoke ("ResetSpeed", Thrusttime);
	}
	
}
